package ru.ganyaev.workstation_vm_manager;

import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

import ru.ganyaev.external_process.ExternalProcessResult;
import ru.ganyaev.utils.BasicFileReader;
import ru.ganyaev.utils.FileReader;
import ru.ganyaev.utils.FileReaderException;

class WorkstationExternalProcessResult extends ExternalProcessResult {
    private static final Charset charset = Charset.forName("cp866");

    private FileReader fileReader = new BasicFileReader();

    private ExternalProcessResult externalProcessResult;
    private List<String> stdOut = new ArrayList<String>();
    private List<String> stdError = new ArrayList<String>();

    public WorkstationExternalProcessResult(
            ExternalProcessResult externalProcessResult, Path stdOutPath,
            Path stdErrorPath) throws WorkstationExternalProcessResultException {
        this.externalProcessResult = externalProcessResult;
        try {
            this.stdOut = fileReader.readLines(stdOutPath, charset);
            this.stdError = fileReader.readLines(stdErrorPath, charset);
        } catch (FileReaderException e) {
            throw new WorkstationExternalProcessResultException(
                    "Can not read stdout('" + stdOutPath + "') or stderror('"
                            + stdErrorPath + "') files.", e);
        }
    }

    @Override
    public List<String> getStdOut() {
        List<String> stdOut = new ArrayList<String>();
        stdOut.add("Workstation stdout:");
        stdOut.addAll(externalProcessResult.getStdOut());
        stdOut.add("Guest stdout:");
        stdOut.addAll(this.stdOut);
        return stdOut;
    }

    @Override
    public List<String> getStdError() {
        List<String> stdError = new ArrayList<String>();
        stdError.add("Workstation stdout:");
        stdError.addAll(externalProcessResult.getStdOut());
        stdError.add("Guest stderror:");
        stdError.addAll(this.stdError);
        return stdError;
    }

    @Override
    public Integer getExitCode() {
        return this.externalProcessResult.getExitCode();
    }

    @Override
    public Boolean isValid() {
        return this.externalProcessResult.isValid();
    }

    @Override
    public String toString() {
        return "WorkstationExternalProcessResult [exitCode=" + getExitCode()
                + ", stdOutput=" + getStdOut() + ", stdError=" + getStdError()
                + "]";
    }
}
